package com.baizhi.controller;

import com.baizhi.entity.Banner;
import com.baizhi.service.BannerService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Controller
@RequestMapping("banner")
public class BannerController {
    @Autowired
    private BannerService bannerService;
    @ResponseBody
    @RequestMapping("selectPageBanner")
    //根据传入的参数进行分页查询展示
    public Map selectPageBanner(Integer page,Integer limit){
        PageInfo<Banner> pageInfo = bannerService.selectAll(page, limit);
        Map map = new HashMap();
        map.put("code",0);
        map.put("msg","");
        map.put("count",pageInfo.getTotal());
        map.put("data",pageInfo.getList());
        return map;
    }
    @ResponseBody
    @RequestMapping("selectOneBanner")
    //查询单条轮播图数据  用于修改的数据回显
    public Banner selectOneBanner(Integer id){
        Banner banner = null;
        System.out.println(" 查询单条方法执行了 ");
        if(id!=null) {
            banner = bannerService.selectOne(id);
        }
        return banner;
    }
    @ResponseBody
    @RequestMapping("insertBanner")
    //添加单条数据
    public Map insertBanner(Banner banner){
        Map map = new HashMap<>();
        System.out.println(" 添加方法执行了 ");
        Boolean res = bannerService.insertBanner(banner);
        map.put("isAdd",res);
        return map;
    }
    @ResponseBody
    @RequestMapping("updateBanner")
    //修改单条数据
    public Map updateBanner(Banner banner){
        Map map = new HashMap<>();
        Boolean res = bannerService.updateBanner(banner);
        map.put("isUpdate",res);
        System.out.println(" 修改方法执行了 "+res);
        return map;
    }
    @ResponseBody
    @RequestMapping("upload")
    //上传图片
    public Map upload(MultipartFile file) throws IOException {
        Map map = new HashMap<>();
        //获取源文件名
        String oldName = file.getOriginalFilename();
        //拼接uuid后的文件名 防止文件名重复上传失败
        String newName = UUID.randomUUID().toString() + oldName;
        //将文件上传到指定路径
        file.transferTo(new File("d://photo",newName));
        //保存两个获取的文件名并返回
        map.put("oldName",oldName);
        map.put("newName",newName);
        return map;
    }
    @ResponseBody
    @RequestMapping("updateStatus")
    //修改图片状态   假删除
    public Map updateStatus(Banner banner){
        Map map = new HashMap<>();
        Boolean res = bannerService.updateStatus(banner);
        map.put("isDelete",res);
        return map;
    }
}
